package com.qingkai.onlineshop.presentation.dashboard

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.qingkai.onlineshop.data.AppDatabase
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

/**
 *作者：created by 89270 on 2025/6/5 10:22
 *描述：
 */
class DashboardViewModel(private val appDatabase: AppDatabase) : ViewModel() {

    private val _mState = MutableStateFlow(DashboardState())
    val state = _mState.onStart {
        initBanners()
        initCategories()
        initItemFulls()
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), _mState.value)

    private fun  initItemFulls() {
        viewModelScope.launch {
            val recommends = appDatabase.itemDao().getRecommendedItems()
            _mState.update { it.copy(itemFulls = recommends) }
        }
    }

    private fun initBanners() {
        viewModelScope.launch {
            val bannerEntities = appDatabase.bannerDao().getAll()
            _mState.update { it.copy(banners = bannerEntities) }
        }
    }

    private fun initCategories() {
        viewModelScope.launch {
            val categoriesEntities = appDatabase.categoryDao().getAll()
            _mState.update { it.copy(categories = categoriesEntities) }
        }
    }


}